package com.agileboot.attendance.domain.order;

import com.agileboot.attendance.domain.order.command.AddOrderPersonnelCommand;
import com.agileboot.attendance.domain.order.command.BatchAddOrderPersonnelCommand;
import com.agileboot.attendance.domain.order.db.AttOrderPersonnelService;
import com.agileboot.attendance.domain.order.dto.OrderDTO;
import com.agileboot.attendance.domain.order.dto.OrderPersonnelDTO;
import com.agileboot.attendance.domain.order.dto.OrderPersonnelQuery;
import com.agileboot.attendance.domain.order.entity.AttOrderPersonnelEntity;
import com.agileboot.attendance.domain.order.model.OrderPersonnelModel;
import com.agileboot.attendance.domain.order.model.OrderPersonnelModelFactory;
import com.agileboot.attendance.domain.personnel.PersonnelApplicationService;
import com.agileboot.attendance.domain.personnel.db.AttPersonnelService;
import com.agileboot.attendance.domain.personnel.db.AttPersonnelEntity;
import com.agileboot.attendance.domain.personnel.dto.PersonnelDTO;
import com.agileboot.attendance.domain.personnel.dto.SearchPersonnelDTO;
import com.agileboot.common.core.page.PageDTO;
import com.agileboot.common.core.page.PageQuery;
import com.agileboot.common.exception.ApiException;
import com.agileboot.common.exception.error.ErrorCode;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单人员关联应用服务
 *
 * @author agileboot
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderPersonnelApplicationService {

    private final AttOrderPersonnelService orderPersonnelService;
    private final AttPersonnelService personnelService;
    private final OrderPersonnelModelFactory orderPersonnelModelFactory;
    private final OrderApplicationService orderApplicationService;
    private final PersonnelApplicationService personnelApplicationService;

    /**
     * 获取订单关联人员列表
     *
     * @param orderId 订单ID
     * @return 人员列表
     */
    public List<OrderPersonnelDTO> getOrderPersonnelList(Long orderId) {
        // 检查订单是否存在
        orderApplicationService.getOrderDetail(orderId);

        return orderPersonnelService.getOrderPersonnelList(orderId);
    }

    /**
     * 分页查询订单关联人员列表
     *
     * @param query 查询参数
     * @return 分页结果
     */
    public PageDTO<OrderPersonnelDTO> getOrderPersonnelPage(OrderPersonnelQuery query) {
        if (query.getOrderId() != null) {
            // 检查订单是否存在
            orderApplicationService.getOrderDetail(query.getOrderId());
        }

        Page<OrderPersonnelDTO> page = orderPersonnelService.getOrderPersonnelPage(query);
        return new PageDTO<>(page.getRecords(), page.getTotal());
    }

    /**
     * 获取可用人员列表，根据订单的供应商进行过滤
     *
     * @param orderId 订单ID
     * @param pageQuery 分页查询参数
     * @return 人员列表
     */
    public PageDTO<PersonnelDTO> getAvailablePersonnelList(Long orderId, PageQuery pageQuery) {
        // 获取订单详情，获取供应商ID
        OrderDTO orderDTO = orderApplicationService.getOrderDetail(orderId);
        if (orderDTO == null || orderDTO.getSupplierId() == null) {
            throw new ApiException(ErrorCode.Business.COMMON_OBJECT_NOT_FOUND, orderId, "订单");
        }

        // 设置查询条件，按订单的供应商ID进行过滤
        SearchPersonnelDTO searchPersonnelDTO = new SearchPersonnelDTO();
        searchPersonnelDTO.setSupplierId(orderDTO.getSupplierId());

        // 已关联的人员ID列表
        List<OrderPersonnelDTO> orderPersonnelList = orderPersonnelService.getOrderPersonnelList(orderId);
        List<Long> excludePersonnelIds = new ArrayList<>();
        for (OrderPersonnelDTO personnel : orderPersonnelList) {
            // 只排除状态为正常的人员
            if ("0".equals(personnel.getStatus())) {
                excludePersonnelIds.add(personnel.getPersonnelId());
            }
        }
        searchPersonnelDTO.setExcludePersonnelIds(excludePersonnelIds);

        // 设置分页参数
        pageQuery.setParam(searchPersonnelDTO);

        // 调用人员服务查询符合条件的人员列表
        return personnelApplicationService.getPersonnelList(pageQuery);
    }

    /**
     * 添加订单人员关联
     *
     * @param command 添加命令
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOrderPersonnel(AddOrderPersonnelCommand command) {
        // 检查订单是否存在
        orderApplicationService.getOrderDetail(command.getOrderId());

        // 检查人员是否存在
        if (personnelService.getById(command.getPersonnelId()) == null) {
            throw new ApiException(ErrorCode.Business.COMMON_OBJECT_NOT_FOUND, command.getPersonnelId(), "人员");
        }

        // 创建模型并检查唯一性
        OrderPersonnelModel model = OrderPersonnelModel.fromCommand(command);
        model.checkUnique(orderPersonnelService);

        // 保存关联
        orderPersonnelService.save(model.getEntity());
    }

    /**
     * 批量添加订单人员关联
     *
     * @param command 批量添加命令
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchAddOrderPersonnel(BatchAddOrderPersonnelCommand command) {
        // 检查订单是否存在
        orderApplicationService.getOrderDetail(command.getOrderId());

        List<AttOrderPersonnelEntity> entityList = new ArrayList<>();

        for (Long personnelId : command.getPersonnelIds()) {
            // 检查人员是否存在
            AttPersonnelEntity personnel = personnelService.getById(personnelId);
            if (personnel == null) {
                throw new ApiException(ErrorCode.Business.COMMON_OBJECT_NOT_FOUND, personnelId, "人员");
            }

            // 检查是否已存在关联
            if (orderPersonnelService.checkOrderPersonnelExists(command.getOrderId(), personnelId)) {
                continue; // 已存在则跳过
            }

            // 创建实体
            AttOrderPersonnelEntity entity = new AttOrderPersonnelEntity();
            entity.setOrderId(command.getOrderId());
            entity.setPersonnelId(personnelId);
            entity.setStartDate(command.getStartDate());
            entity.setEndDate(command.getEndDate());
            entity.setRemark(command.getRemark());
            entity.setMonthlyRate(personnel.getMonthlyRate());
            entity.setStatus("0"); // 正常状态

            entityList.add(entity);
        }

        // 批量保存
        if (!entityList.isEmpty()) {
            orderPersonnelService.saveBatch(entityList);
        }
    }

    /**
     * 解除订单人员关联
     *
     * @param id 关联ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeOrderPersonnel(Long id) {
        // 检查关联是否存在
        OrderPersonnelModel model = orderPersonnelModelFactory.loadById(id);
        if (model == null || model.getEntity() == null) {
            throw new ApiException(ErrorCode.Business.COMMON_OBJECT_NOT_FOUND, id, "订单人员关联");
        }

        // 直接删除关联数据
        orderPersonnelService.removeById(id);
    }
}
